package requesthandler

import (
	"encoding/json"
	"fmt"
	"gitee.com/jamon/espoir_go/common"
	"gitee.com/jamon/espoir_go/common/utils"
	"gitee.com/jamon/espoir_go/global"
	"gitee.com/jamon/espoir_go/logger"
	BaseHandler "gitee.com/jamon/espoir_go/service"
	"tankserver/lib"
)

type AccountPlugin struct {
	BaseHandler.ReqBasePlugin
}

func NewAccountPlugin() *AccountPlugin {
	plugin := &AccountPlugin{
		ReqBasePlugin: BaseHandler.ReqBasePlugin{
			RouteGroupID: lib.RouteGroupID_Default,
			RouteMod:     lib.RouteMod_Default,
			PluginName:   "account",
			MsgBaseID:    lib.MsgID_MODULE_ACCOUNT,
		},
	}

	return plugin
}

func (p *AccountPlugin) Start() (err error) {
	return
}

func (p *AccountPlugin) Stop() error {
	//TODO implement me
	panic("implement me")
}

func (p *AccountPlugin) GetRouteInfo(req *common.MsgRequest) (routeGroupID uint32, subAddress uint32, err error) {
	_, seq, err := common.ParseSessionID(req.SessionID)
	if err != nil {
		return
	}
	subAddress = seq % p.RouteMod
	return p.RouteGroupID, subAddress, nil
}

func (p *AccountPlugin) HandleMsg(req *common.MsgRequest, res *common.MsgResponse) (err error) {
	switch req.MsgId {
	case lib.MsgID_ACCOUNT_REGISTER:
		err = p.handleRegister(req, res)
	case lib.MsgID_ACCOUNT_LOGIN:
		err = p.handleLogin(req, res)
	case lib.MsgID_ACCOUNT_LOGOUT:
		err = p.handleLogout(req, res)
	default:
		err = fmt.Errorf("unknownMsg|account|id=%v", req.MsgId)
	}
	return
}

func (p *AccountPlugin) handleRegister(req *common.MsgRequest, res *common.MsgResponse) (err error) {
	return
}

func (p *AccountPlugin) handleLogin(req *common.MsgRequest, res *common.MsgResponse) (err error) {
	defer func() {
		logger.Info("end", logger.Kwargs{"req_Data": string(req.Data), "res_Data": string(res.Data)})
	}()

	userId := uint64(utils.RandInt(1000000, 9999999))
	res.Data, err = json.Marshal(p.Response(common.MsgCode_SUCCESS, lib.LoginResponse{
		UserID: userId,
	}))
	reqData := lib.LoginRequest{}
	err = json.Unmarshal(req.Data, &reqData)
	global.GetUserManager().AddUser(&common.User{
		UserID:    userId,
		UserName:  reqData.UserName,
		SessionID: req.SessionID,
	})
	return
}

func (p *AccountPlugin) handleLogout(req *common.MsgRequest, res *common.MsgResponse) (err error) {
	defer func() {
		logger.Info("end", logger.Kwargs{"req_Data": string(req.Data), "res_Data": string(res.Data)})
	}()
	reqData := lib.LogoutRequest{}
	err = json.Unmarshal(req.Data, &reqData)
	res.Data, err = json.Marshal(p.Response(common.MsgCode_SUCCESS, lib.LogoutResponse{
		Desc: "logout success",
	}))

	global.GetUserManager().RemoveUserBySessionID(req.SessionID)
	return
}

var accountPlugin BaseHandler.ReqPluginInterface = NewAccountPlugin()

func init() {
	err := BaseHandler.RegisterReqPlugin(lib.MsgID_MODULE_ACCOUNT, &accountPlugin)
	if err != nil {
		panic(err)
	}
}
